package spc.webos.endpoint;

import org.apache.log4j.Logger;
import spc.webos.util.StringX;

public class EndpointFactory {
	static EndpointFactory factory = new EndpointFactory();

	protected Logger log = Logger.getLogger(EndpointFactory.class);

	public Endpoint getEndpoint(String location) throws Exception {
		if (StringX.nullity(location))
			return null;
		location = StringX.trim(location);
		if (ClusterEndpoint.isCluster(location))
			return new ClusterEndpoint(location);
		int idx = location.indexOf(":");
		String protocol = location.substring(0, idx).toLowerCase();
		if (protocol.equals("tcp")) {
			TCPEndpoint endpoint = new TCPEndpoint(location);
			endpoint.init();
			return endpoint;
		}
		if (protocol.equals("class")) {
			int index = location.indexOf(':', 8);
			String strClass = location.substring(6, index);
			String loc = location.substring(index + 1);
			Endpoint endpoint = (Endpoint) Class.forName(strClass)
					.newInstance();
			endpoint.setLocation(loc);
			endpoint.init();
			return endpoint;
		}

		this.log.warn("undefined protocal: " + location);
		return null;
	}

	public static EndpointFactory getInstance() {
		return factory;
	}
}
